<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <div class="nav">
          <span>角色管理</span>
          <el-button type="primary" @click="handleNew" plain :icon="Plus">新增角色</el-button>
        </div>
      </div>
    </template>

    <!--  表格部分 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="#" width="60" />
      <el-table-column prop="rname" label="角色名称" width="180" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="状态" width="180">
        <!-- 列模板内容 -->
        <!-- tr :  当前的表格行
          tr.row ：  表格行绑定的对象 
         :active-value="1"
            :inactive-value="0" ，默认是字符串
        -->
        <template #default="tr">
          <el-switch
            inline-prompt
            @click="statechange(tr.row)"
            v-model="tr.row.nbl"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="Operations" width="220">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            circle
            :icon="Edit"
            @click="handleEdit(scope.$index, scope.row)"
          >
          </el-button>
          <el-button
            size="small"
            :icon="Delete"
            type="danger"
            circle
            @click="handleDelete(scope.$index, scope.row)"
          >
          </el-button>
          <el-button :icon="Key" type="danger" @click="showTree(scope.$index, scope.row)">
            角色授权
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>Footer content</template>
  </el-card>

  <!-- 弹出式对话框 -->
  <el-dialog v-model="dialogVisible" width="500">
    <!-- 自定义头部 -->
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">编辑角色信息</h4>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          关闭
        </el-button>
      </div>
    </template>
    <!-- 对话框内容 -->
    <el-form :model="form">
      <el-form-item label="角色编号" :label-width="formLabelWidth">
        <el-input readonly v-model="form.id" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input clearable v-model="form.rname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input type="textarea" rows="5" clearable v-model="form.remark" autocomplete="off" />
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" :icon="CloseBold"> 取消 </el-button>
        <el-button type="primary" :icon="Promotion" @click="savedata"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  角色抽屉  -->

  <el-drawer v-model="drawer" :direction="direction">
    <template #header>
      <h1>系统功能树</h1>
      <el-button @click="loadtree">加载系统功能树</el-button>
      <el-button @click="setCheckedKeys">加载已有功能</el-button>
    </template>
    <template #default>
      <div>
        <!-- 系统功能树展示区域 -->
        <el-tree
          ref="treeRef"
          node-key="id"
          default-expand-all
          style="max-width: 600px"
          :data="data"
          :props="defaultProps"
          highlight-current
          show-checkbox
        />
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">cancel</el-button>
        <el-button type="primary" @click="confirmClick"> 授权 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import $ajax from 'axios'
import { Plus, Promotion, CloseBold, Delete, Edit, Key } from '@element-plus/icons-vue'
import { ElButton, ElDialog } from 'element-plus'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const drawer = ref(false)
const direction = ref('rtl')

const dialogVisible = ref(false)
const form = ref({
  id: -1,
  rname: '角色',
  remark: '备注',
  nbl: 1
})
const formLabelWidth = 120

let currentidnex = -1
let courrentrole = null
const showTree = (index, row) => {
  courrentrole = row
  drawer.value = true
}

const loadtree = async () => {
  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000
  })
  const { data: res } = await instance.get('/sysnode/select/all/tree')
  if (res.code == 200) {
    const arr = []
    arr.push(res.result)
    data.value = arr
  }
}

const data = ref([
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1'
          }
        ]
      }
    ]
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1'
          }
        ]
      },
      {
        label: 'Level two 2-2',
        children: [
          {
            label: 'Level three 2-2-1'
          }
        ]
      }
    ]
  },
  {
    label: 'Level one 3',
    children: [
      {
        label: 'Level two 3-1',
        children: [
          {
            label: 'Level three 3-1-1'
          }
        ]
      },
      {
        label: 'Level two 3-2',
        children: [
          {
            label: 'Level three 3-2-1'
          }
        ]
      }
    ]
  }
])
const treeRef = ref(null)
const setCheckedKeys = async () => {
  console.log(courrentrole.id)

  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000
  })
  const { data: res } = await instance.get('/role/select/sysnodes/' + courrentrole.id)
  if (res.code === 200) {
    treeRef.value.setCheckedKeys(res.result, false)
  }
}

const confirmClick = async () => {
  const checkedNodeIds = treeRef.value.getCheckedKeys(false)
  const halfCheckedNodeIds = treeRef.value.getHalfCheckedKeys()
  const sids = [...checkedNodeIds, ...halfCheckedNodeIds]

  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
  const { data: res } = await instance.put('/role/auth/' + courrentrole.id, sids)
  console.log(res)
}

const defaultProps = {
  children: 'children',
  label: 'title'
}
const handleEdit = (index, row) => {
  dialogVisible.value = true

  form.value = JSON.parse(JSON.stringify(row))
  currentidnex = index
  console.log(index, row)
}
const handleDelete = (index, row) => {
  console.log(index, row)
}

const savedata = async () => {
  if (form.value.id === -1) {
    adddata()
  } else {
    editdata()
  }
}

const editdata = async () => {
  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
  try {
    const { data: res } = await instance.put('/role/mod', form.value)
    if (res.code === 200) {
      tableData.value[currentidnex] = form.value

      dialogVisible.value = false
      ElMessage({
        showClose: true,
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<strong>This is <i>SUCCESS</i> message</strong>
    <br/>
    <img src="https://gips0.baidu.com/it/u=838505001,1009740821&fm=3028&app=3028&f=PNG&fmt=auto&q=100&size=f254_80"/>
    `
      })
    } else {
      ElMessage({
        showClose: true,
        type: 'error',
        dangerouslyUseHTMLString: true,
        message: `<strong>This is <i>ERROR</i> message</strong>
    <br/>
    ${res.msg}
    <br />
    <img src="https://gips0.baidu.com/it/u=838505001,1009740821&fm=3028&app=3028&f=PNG&fmt=auto&q=100&size=f254_80"/>
    `
      })
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}

const adddata = async () => {
  {
    const instance = $ajax.create({
      baseURL: 'http://localhost:8060',
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
    try {
      const { data: res } = await instance.post('/role/new', form.value)
      if (res.code === 200) {
        form.value.id = res.result
        const temp = JSON.parse(JSON.stringify(form.value))
        tableData.value.push(temp)
        dialogVisible.value = false
        ElMessage({
          showClose: true,
          type: 'success',
          dangerouslyUseHTMLString: true,
          message: `<strong>This is <i>SUCCESS</i> message</strong>
    <br/>
    <img src="https://gips0.baidu.com/it/u=838505001,1009740821&fm=3028&app=3028&f=PNG&fmt=auto&q=100&size=f254_80"/>
    `
        })
      } else {
        ElMessage({
          showClose: true,
          type: 'error',
          dangerouslyUseHTMLString: true,
          message: `<strong>This is <i>ERROR</i> message</strong>
    <br/>
    ${res.msg}
    <br />
    <img src="https://gips0.baidu.com/it/u=838505001,1009740821&fm=3028&app=3028&f=PNG&fmt=auto&q=100&size=f254_80"/>
    `
        })
        console.log(res.msg)
      }
    } catch (error) {
      console.error(error)
    }
  }
}

const tableData = ref([])
const loadrole = async () => {
  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000
  })

  try {
    const { data: res } = await instance.get('/role/s/list/all')
    if (res.code === 200) {
      tableData.value = res.result
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
  console.log('loadrole')
}

const handleNew = () => {
  dialogVisible.value = true
  form.value = { id: -1, rname: '', remark: '' }
}

const statechange = async (row) => {
  const instance = $ajax.create({
    baseURL: 'http://localhost:8060',
    timeout: 5000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
  try {
    const { data: res } = await instance.put('/role/u/byid', row)
    console.log(res.msg)
  } catch (error) {
    console.error(error)
  }
  console.log('loadrole')
  // console.log(row)
}

onMounted(() => {
  loadrole()
})
</script>

<style lang="scss" scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
.el-card {
  .card-header {
    .nav {
      // 弹性盒子,默认支持元素水平摆放
      display: flex;
      // 如果父元素的宽度大于所有子元素宽度之和，、
      // 父元素剩余的空白的处理方法
      justify-content: space-between;
      // 侧轴对齐方式
      align-items: center;
      span {
        font-size: 20px;
        font-weight: 600;
      }
      // .el-button {
      //   background-color: #67c13a;
      // }
    }
  }
}
</style>
